package com.hjy.product.exception;

import com.hjy.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.UnexpectedTypeException;
import java.util.HashMap;
import java.util.Set;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class ExceptionConfiguration {
    // 一般就爆这两个异常
    @ExceptionHandler({ConstraintViolationException.class,BindException.class, MethodArgumentNotValidException.class})
    public R validateException(Exception ex, HttpServletRequest request) {
        ex.printStackTrace();
        String msg = null;
        if(ex instanceof ConstraintViolationException){
            ConstraintViolationException constraintViolationException =
                    (ConstraintViolationException)ex;
            // 获取报错的信息
            Set<ConstraintViolation<?>> violations =
                    constraintViolationException.getConstraintViolations();
            ConstraintViolation<?> next = violations.iterator().next();
            msg = next.getMessage();
        }else if(ex instanceof BindException){
            BindException bindException = (BindException)ex;
            // 获取报错的信息
            msg = bindException.getBindingResult().getFieldError().getDefaultMessage();
        }else {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException)ex;
            BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
            HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
            bindingResult.getFieldErrors().forEach(fieldError -> {
                objectObjectHashMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            });
            return R.error(400,"验证未通过").put("data",objectObjectHashMap);
        }
        return R.error(400,"验证未通过").put("data",msg);
    }
}